﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace OpcUaHelper
{
    /// <summary>
    /// 文本处理Helper
    /// </summary>
    public static class TextHelper
    {
        #region 生成当前时间戳

        /// <summary>
        /// 生成当前时间戳
        /// </summary>
        /// <returns>JSON结果集</returns>
        public static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        #endregion

        #region 生成随机字符串

        ///<summary>
        /// 生成随机字符串
        ///</summary>
        ///<param name="length">目标字符串的长度</param>
        ///<param name="useNum">是否包含数字，true=包含，默认为包含</param>
        ///<param name="useLow">是否包含小写字母，true=包含，默认为包含</param>
        ///<param name="useUpp">是否包含大写字母，true=包含，默认为包含</param>
        ///<param name="useSpe">是否包含特殊字符，true=包含，默认为不包含</param>
        ///<param name="custom">要包含的自定义字符，直接输入要包含的字符列表</param>
        ///<returns>指定长度的随机字符串</returns>
        public static string GetRnd(int length, bool useNum = true, bool useLow = false, bool useUpp = false, bool useSpe = false, string custom = "")
        {
            byte[] b = new byte[4];
            new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
            Random r = new Random(BitConverter.ToInt32(b, 0));
            string s = null, str = custom;
            if (useNum == true) { str += "0123456789"; }
            if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
            //if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
            if (useUpp == true) { str += "ABCDEFGHJKLMNPQRSTUVWXYZ"; }
            if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; }
            for (int i = 0; i < length; i++)
            {
                s += str.Substring(r.Next(0, str.Length - 1), 1);
            }
            return s;
        }

        #endregion

        #region 对字符串进行 SHA1 加密

        /// <summary>
        /// 对字符串进行 SHA1 加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns>JSON结果集</returns>
        public static string SHA1_Encryption(string str)
        {
            // 创建SHA1加密算法对象
            SHA1 sha1 = SHA1.Create();
            // 将原始密码转换为字节数组
            byte[] originalPwd = Encoding.UTF8.GetBytes(str);
            // 执行加密
            byte[] encryPwd = sha1.ComputeHash(originalPwd);
            // 将加密后的字节数组转换为大写字符串
            return string.Join("", encryPwd.Select(b => string.Format("{0:x2}", b)).ToArray()).ToUpper();
        }

        #endregion

        #region RSA加解密

        /// <summary>
        /// 得到RSA公钥私钥
        /// </summary>
        /// <param name="privateKey"></param>
        /// <param name="publicKey"></param>
        public static void RSAGenerateKey(ref string privateKey, ref string publicKey)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            privateKey = rsa.ToXmlString(true);
            publicKey = rsa.ToXmlString(false);
        }

        /// <summary>  
        /// 公钥加密字符串  
        /// </summary>  
        /// <param name="publickey">公钥</param>  
        /// <param name="content">所加密的内容</param>  
        /// <returns>加密后的内容</returns>  
        public static string RSAEncrypt(string publickey, string content)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(publickey);
            cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
            return Convert.ToBase64String(cipherbytes); ;
        }

        /// <summary>  
        /// 私钥解密字符串  
        /// </summary>  
        /// <param name="privatekey">私钥</param>  
        /// <param name="content">加密后的内容</param>  
        /// <returns>解密后的内容</returns>  
        public static string RSADecrypt(string privatekey, string content)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(privatekey);
            cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);
            return Encoding.UTF8.GetString(cipherbytes);
        }

        #endregion

        #region 获取文件编码格式

        /// <summary> 
        /// 给定文件的路径，读取文件的二进制数据，判断文件的编码类型 
        /// </summary> 
        /// <param name=“FILE_NAME“>文件路径</param> 
        /// <returns>文件的编码类型</returns> 
        public static Encoding GetType(string FILE_NAME)
        {
            FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
            Encoding r = GetType(fs);
            fs.Close();
            return r;
        }

        /// <summary> 
        /// 通过给定的文件流，判断文件的编码类型 
        /// </summary> 
        /// <param name=“fs“>文件流</param> 
        /// <returns>文件的编码类型</returns> 
        public static Encoding GetType(FileStream fs)
        {
            byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
            byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
            byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF }; //带BOM 
            Encoding reVal = Encoding.Default;

            BinaryReader r = new BinaryReader(fs, Encoding.Default);
            int.TryParse(fs.Length.ToString(), out int i);
            byte[] ss = r.ReadBytes(i);
            if (IsUTF8Bytes(ss) || (ss[0] == 0xEF && ss[1] == 0xBB && ss[2] == 0xBF))
            {
                reVal = Encoding.UTF8;
            }
            else if (ss[0] == 0xFE && ss[1] == 0xFF && ss[2] == 0x00)
            {
                reVal = Encoding.BigEndianUnicode;
            }
            else if (ss[0] == 0xFF && ss[1] == 0xFE && ss[2] == 0x41)
            {
                reVal = Encoding.Unicode;
            }
            r.Close();
            return reVal;
        }

        /// <summary> 
        /// 判断是否是不带 BOM 的 UTF8 格式 
        /// </summary> 
        /// <param name=“data“></param> 
        /// <returns></returns> 
        private static bool IsUTF8Bytes(byte[] data)
        {
            int charByteCounter = 1; //计算当前正分析的字符应还有的字节数 
            byte curByte; //当前分析的字节. 
            for (int i = 0; i < data.Length; i++)
            {
                curByte = data[i];
                if (charByteCounter == 1)
                {
                    if (curByte >= 0x80)
                    {
                        //判断当前 
                        while (((curByte <<= 1) & 0x80) != 0)
                        {
                            charByteCounter++;
                        }
                        //标记位首位若为非0 则至少以2个1开始 如:110XXXXX...........1111110X 
                        if (charByteCounter == 1 || charByteCounter > 6)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    //若是UTF-8 此时第一位必须为1 
                    if ((curByte & 0xC0) != 0x80)
                    {
                        return false;
                    }
                    charByteCounter--;
                }
            }
            if (charByteCounter > 1)
            {
                throw new Exception("非预期的byte格式");
            }
            return true;
        }

        #endregion

        #region 去除文件bom头后的字符

        /// <summary>
        /// 去除文件bom头后的字符
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static string GetUTF8String(byte[] buffer)
        {
            if (buffer == null)
                return null;

            if (buffer.Length <= 3)
            {
                return Encoding.UTF8.GetString(buffer);
            }

            byte[] bomBuffer = new byte[] { 0xef, 0xbb, 0xbf };

            if (buffer[0] == bomBuffer[0]
                && buffer[1] == bomBuffer[1]
                && buffer[2] == bomBuffer[2])
            {
                return new UTF8Encoding(false).GetString(buffer, 3, buffer.Length - 3);
            }

            return Encoding.UTF8.GetString(buffer);
        }

        #endregion

        #region 根据月份计算季度

        /// <summary>
        /// 根据月份计算季度
        /// </summary>
        /// <param name="month">月份</param>
        public static string CalculateQuarter(int month)
        {
            string ReturnStr;
            if (month <= 3) { ReturnStr = "第一季度"; }
            else if (month <= 6) { ReturnStr = "第二季度"; }
            else if (month <= 9) { ReturnStr = "第三季度"; }
            else { ReturnStr = "第四季度"; }
            return ReturnStr;
        }

        #endregion

        #region 格式化字符串内容

        /// <summary>
        /// 格式化字符串内容
        /// 
        /// (源字符串的字符数量不够时自动补充占位符至指定数量长度)
        /// </summary>
        /// <param name="content">源字符串内容</param>
        /// <param name="placeholder">占位符</param>
        /// <param name="maxCharCount">最大字符数量</param>
        /// <returns></returns>
        public static string FormatString(string content, string placeholder = "0", int maxCharCount = 6)
        {
            //Console.WriteLine($"Content: {content}");
            //Console.WriteLine($"Placeholder: {placeholder}");
            //Console.WriteLine($"MaxCharCount: {maxCharCount}");

            // 如果当前字符串长度等于最大字符数量时则不进行处理
            if (content.Length == maxCharCount)
            {
                Console.WriteLine($"当前字符串长度等于最大字符数量, 不进行处理");
                return content;
            }

            // 将字符串转换为字符List
            List<string> SplitStrData = content.Split(",").ToList();

            // 填充字符串
            for (int i = SplitStrData.Count; i <= maxCharCount; i++)
            {
                SplitStrData.Add(placeholder);
            }

            // 处理后的新字符串
            string newStr = string.Join("", SplitStrData);
            Console.WriteLine($"NewStr: {newStr}");

            return newStr;
        }

        #endregion

        #region 格式化整型数值内容

        /// <summary>
        /// 格式化整型数值内容
        /// 
        /// (源字符串的字符数量不够时自动补充占位符至指定数量长度)
        /// </summary>
        /// <param name="content">整型数值内容</param>
        /// <param name="placeholder">占位符</param>
        /// <param name="maxCharCount">最大字符数量</param>
        /// <returns></returns>
        public static string FormatIntToString(string content, string placeholder = "0", int maxCharCount = 3)
        {
            //Console.WriteLine($"Content: {content}");
            //Console.WriteLine($"Placeholder: {placeholder}");
            //Console.WriteLine($"MaxCharCount: {maxCharCount}");

            // 如果当前字符串长度等于最大字符数量时则不进行处理
            if (content.Length == maxCharCount)
            {
                Console.WriteLine($"当前字符串长度等于最大字符数量, 不进行处理");
                return content;
            }

            // 将字符串转换为字符List
            List<string> SplitStrData = new List<string>();

            // 填充字符串
            for (int i = 1; i <= maxCharCount - content.Length; i++)
            {
                SplitStrData.Add(placeholder);
            }
            SplitStrData.Add(content);

            // 处理后的新字符串
            string newStr = string.Join("", SplitStrData);
            Console.WriteLine($"NewStr: {newStr}");

            return newStr;
        }

        #endregion

    }
}
